﻿package com.manyiaby.view.viewutils;

import android.graphics.Bitmap;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

/**
 * 帮助WebView处理一些页面控制和请求通知还可以重写很多方法
 */
public class MyWebViewClient extends WebViewClient {
    WebSettings webSettings=null;
    ProgressBar progressBar;
    public MyWebViewClient() {
    }

    public MyWebViewClient(WebSettings webSettings) {
        this.webSettings = webSettings;
    }

    public MyWebViewClient(WebSettings webSettings, ProgressBar progressBar) {
        this.webSettings = webSettings;
        this.progressBar=progressBar;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
//        webSettings.setBlockNetworkImage(true);//延迟网络图片加载
        if(progressBar!=null){
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        // 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
        view.loadUrl("file:///android_asset/error.html");
    }

    @Override
    public void onPageFinished(WebView view, String url) {
//        webSettings.setBlockNetworkImage(false);//停止延迟网络图片加载
        if(progressBar!=null){
            progressBar.setVisibility(View.GONE);
        }
        addImgClickListener(view);
        reWebViewMeasure(view);
    }

    /**
     * 给WebView的img标签设置点击事件
     * @param view
     */
    private void addImgClickListener(WebView view) {
        view.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.local_obj.showSource(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }

    /**
     * 重新计算WebView的高度
     * @param view
     */
    private void reWebViewMeasure(WebView view) {
        //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
        //设置setWebViewClient且设置WebView高度为wrap_content防止ScrollView嵌套WebView出现大面积空白问题
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        //重新测量
        view.measure(w, h);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // 返回true 控制网页在webview中打开
        // false 则是调用系统浏览器 或者第三方浏览器
        view.loadUrl(url);
        return true;
    }
}
